package com.gcloud.controller.storage.timer;

import java.text.SimpleDateFormat;

import org.quartz.CronScheduleBuilder;
import org.quartz.DisallowConcurrentExecution;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.PersistJobDataAfterExecution;
import org.quartz.ScheduleBuilder;
import org.quartz.Trigger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.gcloud.controller.storage.prop.StorageProp;
import com.gcloud.controller.storage.service.IStoragePoolService;
import com.gcloud.core.quartz.GcloudJobBean;
import com.gcloud.core.quartz.annotation.QuartzTimer;
import com.gcloud.header.compute.enums.StorageType;

import lombok.extern.slf4j.Slf4j;

/**
Copyright (c) [2020] [G-CLOUD TECHNOLOGY] [G-Cloud 8.0] is licensed under the Mulan PSL v1.
You can use this software according to the terms and conditions of the Mulan PSL v1. You may obtain
a copy of Mulan PSL v1 at: http://license.coscl.org.cn/MulanPSL THIS SOFTWARE IS PROVIDED ON AN 
"AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 
TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. See the Mulan PSL v1 for more details.
 */

@Component
@PersistJobDataAfterExecution
@DisallowConcurrentExecution
@QuartzTimer //"${gcloud.controller.storage.pool.cron:0 */1 * * * ?}"
@Slf4j
public class CollectStorageInfoCron  extends GcloudJobBean{
	@Autowired
	IStoragePoolService storagePoolService;
	
	@Autowired
	StorageProp storageProp;
	
	static SimpleDateFormat timeF = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	
	@Override
	protected void executeInternal(JobExecutionContext context) throws JobExecutionException {
		try {
			//SchedulerFactoryBean(747):? Starting Quartz Scheduler now, after delay of 2 seconds 有时候quartz会延迟几秒执行，导致批次跟节点上的不一致
			String batchId = timeF.format(context.getFireTime());
			log.debug("收集存储池信息批次：" + batchId);
			batchId = "1fixedBatchId";//暂时先固定一个批次，相当于只是定时汇报存储池信息
			
			//初始化批次任务信息（失去连接的节点的本地存储池不记录）
			storagePoolService.initCollectStorageInfoCron(batchId);
			
			//控制节点收集ceph、lvm存储池信息
			String[] storageTypes = {StorageType.DISTRIBUTED.getValue(), StorageType.CENTRAL.getValue()};
			storagePoolService.collectStorageInfos(batchId, storageTypes);
		}catch(Exception ex) {
			log.error("CollectStorageInfoCron 失败", ex);
		}
	}
	
	public ScheduleBuilder<? extends Trigger> scheduleBuilder(){
		log.debug("CollectStorageInfoCron cron:" +storageProp.getPoolCollectCron());
		return CronScheduleBuilder.cronSchedule(storageProp.getPoolCollectCron()).withMisfireHandlingInstructionDoNothing();
	}
}
